package com.biwano.swapmyjob.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

public abstract class BaseDao<T> {

	public abstract EntityManager getEntityManager();
	public abstract Class<T> getClazz();
	
	public boolean entityExists(Object key)
	{
		return (getEntityManager().find(getClazz(), key)!=null);
	}
	public void removeEntity(Object key) throws DBException
	{
		getEntityManager().remove(findEntity(key));
	}
	public T findEntity(Object key) throws DBException
	{
		T t = getEntityManager().find(getClazz(), key);
		if (t==null) throw new DBException();
		return t;
	}
	public boolean entityExists(String param, Object value)
	{
		TypedQuery<T> q = getEntityManager().createQuery("Select o from " + getClazz().getSimpleName() + " o " +
				" where o." + param + " = :value", getClazz());
		q.setParameter("value", value);
		
		return (q.getResultList().size()>0);
	}
	public void drop()
	{
		Query q = getEntityManager().createQuery("delete from " + getClazz().getSimpleName() );
		q.executeUpdate();
	}
	public void persist(T o)
	{
		getEntityManager().persist(o);
	}
	public List <T> getAllEntities()
	{
		TypedQuery<T> q = getEntityManager().createQuery("select o from " + getClazz().getSimpleName() + " o", getClazz());
		
		return q.getResultList();
	}

}
